package company.receipt;

import java.util.*;

public class Permutations {

    public static void main(String[] args) {
        Integer[] arr = {1, 2, 3};
        List<List<Integer>> permutations = generatePermutations(arr);
        System.out.println(permutations);
    }

    public static List<List<Integer>> generatePermutations(Integer[] arr) {
        Set<List<Integer>> result = new HashSet<>();
        generatePermutations(arr, new ArrayList<>(), result);
        return new ArrayList<>(result);
    }

    private static void generatePermutations(Integer[] arr, List<Integer> current, Set<List<Integer>> result) {
        if (current.size() == arr.length) {
            int sum = current.stream().mapToInt(Integer::intValue).sum();
            for (List<Integer> list : result) {
                if (list.stream().mapToInt(Integer::intValue).sum() == sum) {
                    return;  // discard current permutation if its sum already exists
                }
            }
            result.add(new ArrayList<>(current));
            return;
        }
        for (int i = 0; i < arr.length; i++) {
            if (current.contains(arr[i])) {
                continue;
            }
            current.add(arr[i]);
            generatePermutations(arr, current, result);
            current.remove(current.size() - 1);
        }
    }
}
